package com.cn.springcloudwechat.service.personalcenter.serviceImpl;

import com.cn.springcloudwechat.common.utils.ThreadLocalUtil;
import com.cn.springcloudwechat.common.utils.TimeUtil;
import com.cn.springcloudwechat.mapper.mapper.YmUserSignInMapper;
import com.cn.springcloudwechat.model.YmUserSignIn;
import com.cn.springcloudwechat.model.dto.SignInDto;
import com.cn.springcloudwechat.service.personalcenter.service.YmUserSignInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Lg
 * @Date 2018/8/6 9:49
 * @Content
 */
@Service("YmUserSignInService")
public class YmUserSignInServiceImpl implements YmUserSignInService{

    @Autowired
    YmUserSignInMapper ymUserSignInMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertUserSignIn() throws ParseException {
        Long userId = ThreadLocalUtil.getUser().getUserId();
        YmUserSignIn userSignIn = ymUserSignInMapper.getNewestSignIn(userId);
        long days = 2;
        if(userSignIn != null){
            days = TimeUtil.getTimeDifference(userSignIn);
        }
        if(days == 0){
            throw new IllegalArgumentException("今日已签到，请勿重复签到");
        }
        YmUserSignIn ymUserSignIn = new YmUserSignIn();
        if(days == 1){
            ymUserSignIn.setSignInDays(userSignIn.getSignInDays()+1);
        }else {
            ymUserSignIn.setSignInDays(1);
        }
        ymUserSignIn.setUserId(userId);
        return ymUserSignInMapper.insertSelective(ymUserSignIn);
    }

    @Override
    public SignInDto getContinuousSignInDay() throws ParseException {

        Long userId = ThreadLocalUtil.getUser().getUserId();
        YmUserSignIn ymUserSignIn = ymUserSignInMapper.getNewestSignIn(userId);
        SignInDto signInDto = new SignInDto();
        if(ymUserSignIn != null){
            long days = TimeUtil.getTimeDifference(ymUserSignIn);
            if(days>1){
                signInDto.setSignInDays(0);
            }else {
                signInDto.setSignInDays(ymUserSignIn.getSignInDays());
                if(days==1){
                    signInDto.setIsSignIn(0);
                }else {
                    signInDto.setIsSignIn(1);
                }
            }
        }else {
            signInDto.setIsSignIn(0);
            signInDto.setSignInDays(0);
        }
        return signInDto;
    }
}
